import { FC, useEffect, useState } from 'react'
import styles from './ChatInput.module.scss'
import lang from './ChatInput.i18n.json'
import { useStyles } from '@/hooks/styles'
import { Input, message } from 'antd'
import { useLang } from '@/hooks/i18n'
import { motion } from 'framer-motion'
import { motionEasing } from '@/config'
import { SvgIcon } from '@/components/icons'
import { PaperAirplane } from '@/components/icons/PaperAirplane'
import { useChatStore } from '@/hooks'
import axios from 'axios'
import { observer } from 'mobx-react'

interface IChatInput {
  scrollToBottom?: () => void
  onSend?: (humanMessage: string) => void
}
export const ChatInput: FC<IChatInput> = observer(
  ({ scrollToBottom, onSend }) => {
    const styleClass = useStyles(styles)
    const { t } = useLang(lang, 'ChatInput')
    const chatStore = useChatStore()
    const [messageApi, contextHolder] = message.useMessage()
    // const [userInput, setUserInput] = useState<string>('')
    const handleKeyDown = (e) => {
      if (e.ctrlKey && e.key === 'Enter') {
        handleSend()
        return
      }
    }
    const [test, setTest] = useState(axios.CancelToken.source())

    const handleSend = async () => {
      if (chatStore.userInput !== '') {
        const originHistory = [...chatStore.history]
        if (
          chatStore.history[chatStore.history.length - 1].content !==
          chatStore.userInput
        ) {
          chatStore.addHistory('human', chatStore.userInput)
        }
        setTimeout(() => chatStore.addHistory('ai', '------'), 1000)
        chatStore.setTyping(true)
        await axios
          .post(
            'https://sustain-kg.littleor.cn/chat',
            {
              history: originHistory,
              message: chatStore.userInput,
            },
            { cancelToken: test.token }
          )
          .then((res) => {
            chatStore.replaceContent(res.data.data)
            console.log(res.data)
            const temp1 = {
              nodes_get: res.data.node.nodes_trans,
              links_get: res.data.node.links_trans,
            }
            chatStore.setGraphData(temp1)
            chatStore.setRecommendNode(res.data.recommend_node)
            chatStore.setTyping(false)
            // scrollToBottom && scrollToBottom()
            chatStore.setUserInput('')
            return
          })
          .catch((error) => {
            if (axios.isCancel(error)) {
              chatStore.setTyping(false)
              chatStore.popHistory()
              chatStore.setReStart(false)
              console.log('手动取消')
            } else {
              chatStore.setTyping(false)
              chatStore.popHistory()
              console.error('请求失败：', error)
            }
          })
      } else {
        // 输入框为空
        messageApi.info({ content: '输入内容为空！' })
      }
    }

    useEffect(() => {
      if (chatStore.reStart === true) {
        test.cancel('重新发送请求的原因')
        setTest(axios.CancelToken.source())
      }
    }, [chatStore.reStart])

    return (
      <div {...styleClass(['layout'])}>
        {contextHolder}
        <Input.TextArea
          {...styleClass(['textarea'])}
          placeholder={t`Please enter \nCtrl+Enter: Send `}
          autoSize={{ minRows: 3, maxRows: 5 }}
          value={chatStore.userInput}
          onChange={(e) => chatStore.setUserInput(e.target.value)}
          onKeyDown={(e) => handleKeyDown(e)}
        />
        <div {...styleClass(['send-button-wrapper'])}>
          <SendButton onClick={() => handleSend()} />
        </div>
      </div>
    )
  }
)

interface ISendButton {
  onClick?: () => void
}
const SendButton: FC<ISendButton> = ({ onClick }) => {
  const { t } = useLang(lang, 'ChatInput')
  const styleClass = useStyles(styles)

  const [ifHover, setIfHover] = useState<boolean>(false)
  const [maskAnimation, setMaskAnimation] = useState<boolean>(false)

  const onButtonTap = () => {
    setMaskAnimation(true)
    setTimeout(() => setMaskAnimation(false), 500)
    onClick()
  }
  return (
    <motion.div
      {...styleClass(['send-button-layout'])}
      onMouseEnter={() => setIfHover(true)}
      onMouseLeave={() => setIfHover(false)}
      animate={{
        y: ifHover ? -3 : 0,
        boxShadow: ifHover
          ? '0 3px 4px 0 rgba(0, 0, 0, 0.25)'
          : '0 3px 4px 0 rgba(0, 0, 0, 0.1)',
      }}
      transition={{ ...motionEasing, duration: 0.3 }}
      whileTap={{
        background: 'linear-gradient(140deg, #7032F4 0%, #4C07DF 100%)',
      }}
      onClick={onButtonTap}
    >
      {maskAnimation && (
        <motion.div
          {...styleClass(['send-button-mask'])}
          initial={{ scale: 1, opacity: '25%' }}
          animate={{ scale: 1.3, opacity: '0%' }}
          transition={{ ...motionEasing, duration: 0.5 }}
        ></motion.div>
      )}
      <motion.div
        {...styleClass(['send-button-prefix-wrapper'])}
        animate={{
          background: ifHover
            ? 'rgba(255,255,255,0.5)'
            : 'rgba(255,255,255,0.3)',
        }}
        transition={{ ...motionEasing, duration: 0.3 }}
      >
        <motion.div
          {...styleClass(['send-button-prefix-item'])}
          animate={{ rotateZ: ifHover ? 45 : 0, x: ifHover ? -1.5 : 0 }}
        >
          <SvgIcon icon={PaperAirplane}></SvgIcon>
        </motion.div>
      </motion.div>
      <div {...styleClass(['send-button-text'])}>{t`Send`}</div>
    </motion.div>
  )
}
